import Sheet from "@/components/Sheet";
import axios from 'axios'
import { Card, Space, Button, DatePicker, Select, Modal, Tabs, message, Upload, Input, Flex, Typography, Popconfirm } from "antd";
import { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import BtnTool from "@/components/BtnTool";
import { setShowBtnTool } from "@/store/modules/style";
import { sikuhshsearchtplAPI, sikuhshuploadAPI, sikuhshuploadtplAPI, sikuhshclearAPI, sikuhshdeletealltplAPI } from "@/apis";
import { InboxOutlined, DownloadOutlined, SyncOutlined } from '@ant-design/icons';
import VerifyHshModal from "./VerifyHshModal/index";

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { Dragger } = Upload;
const { Text } = Typography;
const columns = [
  {
    title: '批次号',
    dataIndex: 'PCH',
  },
  {
    title: '创建人',
    dataIndex: 'CREATOR',
  },
  {
    title: '创建时间',
    dataIndex: 'CREATE_TIME',
  },
  {
    title: '序号',
    dataIndex: 'ID',
  },
  {
    title: '编号',
    dataIndex: 'CODE',
  },
  {
    title: '分析报告批次',
    dataIndex: 'FXBGPC' 
  },
  {
    title: '提供时间',
    dataIndex: 'TGSJ'
  },
  {
    title: '所属二级',
    dataIndex: 'SSEJ'
  },
  {
    title: '成员单位',
    dataIndex: 'CYDW'
  },
  {
    title: '交易对手',
    dataIndex: 'JYDS'
  },
  {
    title: '涉险类型',
    dataIndex: 'SXLX'
  },
  {
    title: '交易类型',
    dataIndex: 'JYLX'
  },
  {
    title: '交易笔数',
    dataIndex: 'JYBS'
  },
  {
    title: '交易金额（万元）',
    dataIndex: 'JYJE'
  },
  {
    title: '反馈情况',
    dataIndex: 'FKQK'
  },
  {
    title: '命中情况',
    dataIndex: 'MZQK'
  }
]

export default function UploadHshModal({ onrefresh }) {
    // 日期类型选择器
    const [type, setType] = useState('year');
    // 存储日期
    const [range, setRange] = useState([]);
    // 分页参数
    const [page, setPage] = useState({ pageNum: 1, pageSize: 10 });
    // 选中行
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);
    // 数据源
    const [dataSource, setDataSource] = useState({ data: [], total: 0 });
    // 搜索参数状态
    const [searchParams, setSearchParams] = useState({});
    // 加载状态
    const [loading, setLoading] = useState(false); 
    // 控制弹出框状态，默认关闭
    const [isModalOpen, setIsModalOpen] = useState(false);
    const dispatch = useDispatch();
    // 打开弹出框
    const showModal = () => {
        setIsModalOpen(true);
    };
    // 弹出框确认按钮事件
    const handleOk = () => {
        setIsModalOpen(false);
    };
    // 弹出框取消按钮事件
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 获取数据方法
    const fetchData = async () => {
        setLoading(true);
        try {
            const res = await sikuhshsearchtplAPI({
                pagenum: page.pageNum,
                pagesize: page.pageSize
            });
            
            // 根据实际API响应结构调整
            setDataSource({
                data: res.data.data || [],
                total: res.data.total || 0
            });
        } catch (error) {
            console.error('数据获取失败:', error);
        } finally {
            setLoading(false);
        }
    };
    // 当page或searchParams变化时重新获取数据
    useEffect(() => {
        fetchData();
    }, [page]);

    const handlePage = (pageNum, pageSize) => {
        setPage({ pageNum, pageSize });
    };
    const handleSelChange = (keys, rows) => {
        setSelectedRowKeys(keys);
        setSelectedRows(rows)
        dispatch(setShowBtnTool(keys.length > 0));
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: handleSelChange,
    };
    // 删除
    const handleDel = () => {
        // console.log('删除的 keys:', selectedRowKeys);
        // console.log('删除的数据:', selectedRows);
        let ids = {
            "ids": selectedRowKeys
        }
        sikuhshdeletealltplAPI({
            params: ids
        }).then((res) => {
            if (res.code == 200){
                message.success(res.message);
                // 刷新数据
                fetchData();
            }else{
                message.error(res.message);
            }
        }).catch(() => {
            message.error("删除失败！")
        })
    };
    // 模板下载
    const report_download = () => {
        axios.get(`http://192.168.1.188:9000/kshx/download-hshtplfile`, {
            responseType: 'blob', 
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('kshxtoken')
            }
        }).then(res => {
            const blob = new Blob([res.data], { type: res.headers['content-type'] });
            let fileName = '核实函模板.xlsx'; // 默认名
            // 创建下载链接并触发下载
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        }).catch(err => {
            console.error('文件下载失败:', err);
        });
    }
    const PickerWithType = ({ type, value, onChange }) => {
        return <RangePicker picker={type} value={value} onChange={onChange} />;
    };
    const handleDateChange = (value) => {
        if (!value || value.length !== 2) {
            return;
        }
        const [start, end] = value;
        // 格式化成字符串
        const startStr = start.format(type === 'year' ? 'YYYY' : 'YYYY-MM');
        const endStr = end.format(type === 'year' ? 'YYYY' : 'YYYY-MM');
        // 放入请求参数中
        setSearchParams({ type: type, starttime: startStr, endtime: endStr });
    };
    const props_tbth = {
        name: 'file',
        multiple: true,
        customRequest({ file, onSuccess, onError }) {
            sikuhshuploadtplAPI(file)
            .then((res) => {
                if (res.code == 200){
                    message.success(`${file.name} 上传成功！`);
                    // 刷新数据
                    fetchData();
                    onSuccess();
                }else{
                    message.error(`${file.name} 上传失败！`);
                    onError(res.message);
                }
            })
            .catch((err) => {
                console.error('上传失败', err);
                message.error(`${file.name} 上传失败！`);
                onError(err);
            });
        },
        onChange(info) {
            const { status } = info.file;
            if (status !== 'uploading') {
                console.log('当前文件状态:', info.file);
            }
        },
        onDrop(e) {
            console.log('拖拽上传文件:', e.dataTransfer.files);
        }
    };
    const props_zlgx = {
        name: 'file',
        multiple: true,
        customRequest({ file, onSuccess, onError }) {
            sikuhshuploadAPI(file)
            .then((res) => {
                if (res.code == 200){
                    message.success(`${file.name} 上传成功！`);
                    onrefresh();
                    onSuccess();
                }else{
                    message.error(`${file.name} 上传失败！`);
                    onError(res.message);
                }
            })
            .catch((err) => {
                console.error('上传失败', err);
                message.error(`${file.name} 上传失败！`);
                onError(err);
            });
        },
        onChange(info) {
            const { status } = info.file;
            if (status !== 'uploading') {
                console.log('当前文件状态:', info.file);
            }
        },
        onDrop(e) {
            console.log('拖拽上传文件:', e.dataTransfer.files);
        }
    };
    const confirm = e => {
        sikuhshclearAPI().then((res) => {
            if (res.code == 200){
                message.success("删除成功！");
                fetchData();
            }else{
                message.error("删除失败！");
            }
        }).catch((err) => {
            console.error('删除失败', err);
            message.error("删除失败！");
        })
    };
    return (
        <div>
            <div
                onClick={report_download}
                style={{
                    border: '1px dashed #1890ff',
                    borderRadius: 8,
                    padding: '20px 20px',
                    textAlign: 'center',
                    cursor: 'pointer',
                    backgroundColor: '#fafafa',
                }}
                >
                <DownloadOutlined style={{ fontSize: 40, color: '#1890ff' }} />
                <div style={{ marginTop: 16 }}>
                    <Text strong>点击此处下载核实函模板</Text>
                    <br />
                    <Text type="secondary">请使用正确格式的模板。不要修改头文件。</Text>
                </div>
            </div>
            <Tabs defaultActiveKey="1" centered>
                <TabPane tab="核实函同步替换" key="1">
                    <Flex vertical='vertical'>
                        <div>
                            <span>请选择同步替换的时间区间：</span>
                            <Space>
                                <Select aria-label="Picker Type" value={type} onChange={setType}>
                                    <Option value="year">年份</Option>
                                    <Option value="month">月份</Option>
                                </Select>
                                <PickerWithType type={type} value={range} onChange={(value) => {
                                    setRange(value);
                                    handleDateChange(value);
                                }} />
                            </Space>
                        </div>
                        <div style={{ marginTop: '20px' }}>
                            <Dragger {...props_tbth}>
                                <p className="ant-upload-drag-icon">
                                    <InboxOutlined />
                                </p>
                                <p className="ant-upload-text">点击选择文件或拖拽文件上传</p>
                                <p className="ant-upload-hint">支持单个或批量上传。</p>
                            </Dragger>
                        </div>
                        <div style={{ marginTop: '20px' }}>
                            <Flex justify={'flex-end'} align={'flex-start'}>
                                <Space>
                                    <Button type="primary" shape="circle" icon={<SyncOutlined spin={loading} />} onClick={fetchData}/>
                                    <Button type="primary">校验数据</Button>
                                    <Popconfirm
                                        title="清空数据"
                                        description="该操作将会清空所有数据，确认删除？"
                                        onConfirm={confirm}
                                        okText="确认"
                                        cancelText="取消"
                                    >
                                        <Button type="primary" danger>清空数据</Button>  
                                    </Popconfirm>
                                    <Button type="primary" style={{
                                        backgroundColor: '#67C23A',
                                        borderColor: '#67C23A',
                                        color: 'white',
                                    }} onClick={showModal}>上传数据</Button>
                                </Space>
                            </Flex>    
                            <Modal
                                title="同步替换预览"
                                closable={{ 'aria-label': 'Custom Close Button' }}
                                open={isModalOpen}
                                onOk={handleOk}
                                onCancel={handleCancel}
                                width={1500}
                                footer={null}
                            >
                                <VerifyHshModal params={searchParams}/>
                            </Modal>
                        </div>
                        <div>
                            <Sheet 
                                columns={columns} 
                                dataSource={{
                                    data: dataSource.data,
                                    total: dataSource.total
                                }} 
                                rowSelection={rowSelection} 
                                rowKey='ID' 
                                page={page} 
                                onChange={handlePage}
                                loading={loading}
                            />
                        </div> 
                    </Flex>
                </TabPane>
                <TabPane tab="核实函增量更新" key="2">
                    <Dragger {...props_zlgx}>
                        <p className="ant-upload-drag-icon">
                            <InboxOutlined />
                        </p>
                        <p className="ant-upload-text">点击选择文件或拖拽文件上传</p>
                        <p className="ant-upload-hint">支持单个或批量上传。</p>
                    </Dragger>
                </TabPane>
            </Tabs>
            <BtnTool 
                total={`已选择 ${selectedRowKeys.length} 项`} 
                isShow={selectedRowKeys.length > 0} 
                isSave={false} 
                onDel={handleDel}
                isFixed={false}
            />
        </div>
    )
}